package cn.piesat.service.impl;

import cn.piesat.mapper.UserInfoConfigMapper;
import cn.piesat.dao.PiesatUserConfigInfoDAO;
import cn.piesat.dao.PiesatUserInfoConfigDAO;
import cn.piesat.dto.PiesatUserInfoConfigDTO;
import cn.piesat.service.intf.UserInfoConfigService;
import cn.piesat.vo.userInfoConfig.AddUserInfoConfigVO;
import cn.piesat.vo.userInfoConfig.PartUserInfoConfigVO;
import cn.piesat.vo.userInfoConfig.UserInfoConfigVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户配置项信息服务层逻辑实现
 *
 * @author xhl
 */
@Service
public class UserInfoConfigServiceImpl implements UserInfoConfigService {

    @Autowired
    private PiesatUserInfoConfigDAO piesatUserInfoConfigDAO;

    @Autowired
    private PiesatUserConfigInfoDAO piesatUserConfigInfoDAO;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> save(List<AddUserInfoConfigVO> dataList) {
        Map<String,String> resultMap = new HashMap<>();
        Map<String,AddUserInfoConfigVO> fieldHash = new HashMap<>();
        Map<String,AddUserInfoConfigVO> fieldNameHash = new HashMap<>();
        //校验参数字段标识和名称是否重复，选择为登录项必须选择注册项，选择为搜索项必须选择注册项
        List<PiesatUserInfoConfigDTO> userInfoConfigList = new ArrayList<>();
        for (AddUserInfoConfigVO userInfoConfigDTO : dataList) {
            String field = userInfoConfigDTO.getField();
            String fieldName = userInfoConfigDTO.getFieldName();
            if (fieldHash.containsKey(field)) {
                resultMap.put("success","false");
                resultMap.put("message","字段标识" + field + "重复");
                return resultMap;
            }
            if (fieldNameHash.containsKey(fieldName)) {
                resultMap.put("success","false");
                resultMap.put("message","字段名称" + fieldName + "重复");
                return resultMap;
            }
            //0：是;1：否
            Integer isNotLogin = userInfoConfigDTO.getIsNotLogin();
            Integer isNotSearch = userInfoConfigDTO.getIsNotSearch();
            Integer isNotRegister = userInfoConfigDTO.getIsNotRegister();
            if (isNotLogin == 0 && isNotRegister == 1) {
                resultMap.put("success","false");
                resultMap.put("message","选择" + fieldName + "为登录项必须选择其为注册项");
                return resultMap;
            }
            if (isNotSearch == 0 && isNotRegister == 1) {
                resultMap.put("success","false");
                resultMap.put("message","选择" + fieldName + "为搜索项必须选择其为注册项");
                return resultMap;
            }
            fieldHash.put(field,userInfoConfigDTO);
            fieldNameHash.put(fieldName,userInfoConfigDTO);
            if (StringUtils.isBlank(userInfoConfigDTO.getId())) {
                userInfoConfigDTO.setCreateTime(new Date());
            }
            PiesatUserInfoConfigDTO piesatUserInfoConfigDTO = UserInfoConfigMapper.INSTANCE
                    .userInfoConfigDtoToUserInfoDo(userInfoConfigDTO);
            userInfoConfigList.add(piesatUserInfoConfigDTO);
        }
        boolean hasLogin = false;
        String[] loginMark = {"username","email","telephone","password"};
        for (String mark : loginMark) {
            if (fieldHash.containsKey(mark)) {
                AddUserInfoConfigVO userInfoConfigDTO = fieldHash.get(mark);
                if (userInfoConfigDTO.getIsNotLogin() == 0) {
                    hasLogin = true;
                    break;
                }
            }
        }
        if (!hasLogin) {
            resultMap.put("success","false");
            resultMap.put("message","至少选择一种登录项");
            return resultMap;
        }
        //如果在普通输入框下 没有选择密码 则无效
        if(fieldHash.containsKey("password") && fieldHash.get("password").getIsNotLogin() == 1){
            List<AddUserInfoConfigVO> configList = new ArrayList<>(3);
            for (int i = 0 ; i < loginMark.length - 1 ; i ++){
                AddUserInfoConfigVO c = null;
                if(fieldHash.containsKey(loginMark[i])){
                    c = fieldHash.get(loginMark[i]);
                }
                configList.add(c);
            }
            int count = 0;
            for (AddUserInfoConfigVO c : configList){
                if (c.getIsNotLogin() == 0 && c.getFormType().equals("input")){
                    count++;
                }
            }
            if (count > 0){
                resultMap.put("message", "不能只配置普通输入框类型字段而不配置密码");
                resultMap.put("success", "false");
                return resultMap;
            }
        }
        if (fieldHash.containsKey("password") && fieldHash.get("password").getIsNotLogin() == 0){
            int noLoginCount = 0;
            for (int i = 0 ; i < loginMark.length - 1 ; i ++){
                AddUserInfoConfigVO c = null;
                if(fieldHash.containsKey(loginMark[i])){
                    c = fieldHash.get(loginMark[i]);
                    if (c.getIsNotLogin() == 1){
                        noLoginCount++;
                    }
                }
            }
            if (noLoginCount == 3){
                resultMap.put("msg", "不能只配置密码框类型字段");
                resultMap.put("success", "false");
                return resultMap;
            }
        }
        piesatUserInfoConfigDAO.saveAll(userInfoConfigList);
        resultMap.put("success","true");
        resultMap.put("message","保存成功");
        return resultMap;
    }

    @Override
    public List<UserInfoConfigVO> list() {
        List<PiesatUserInfoConfigDTO> dataList = piesatUserInfoConfigDAO.findAllByOrderByCreateTime();
        return dataList.stream()
                .map(UserInfoConfigMapper.INSTANCE::userInfoConfigDoToUserInfoConfigVo)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String id) {
        piesatUserInfoConfigDAO.deleteById(id);
        piesatUserConfigInfoDAO.deleteAllByUserConfigId(id);
    }

    @Override
    public List<PartUserInfoConfigVO> listConfigView(String type) {
        List<PartUserInfoConfigVO> dataList = null;
        if ("register".equals(type)) {
            List<PiesatUserInfoConfigDTO> list = piesatUserInfoConfigDAO.findAllByIsNotRegisterOrderByCreateTime(0);
            dataList = list.stream()
                    .map(UserInfoConfigMapper.INSTANCE::userInfoConfigDto2RegisterConfigVo)
                    .collect(Collectors.toList());
        } else if ("login".equals(type)) {
            List<PiesatUserInfoConfigDTO> list = piesatUserInfoConfigDAO.findAllByIsNotLoginOrderByCreateTime(0);
            dataList = list.stream()
                    .map(UserInfoConfigMapper.INSTANCE::userInfoConfigDto2LoginConfigVo)
                    .collect(Collectors.toList());
        } else if ("search".equals(type)) {
            List<PiesatUserInfoConfigDTO> list = piesatUserInfoConfigDAO.findAllByIsNotSearchOrderByCreateTime(0);
            dataList = list.stream()
                    .map(UserInfoConfigMapper.INSTANCE::userInfoConfigDto2SearchConfigVo)
                    .collect(Collectors.toList());
        } else {
            dataList = new ArrayList<>();
        }
        return dataList;
    }
}
